package com.xcc.common.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xcc.common.config.login.LoginConfig;
import com.xcc.common.page.PageParam;
import com.xcc.common.redis.RedisUtil;
import com.xcc.common.result.ResultBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xcc.common.domain.mapper.UserMapper;
import com.xcc.common.domain.entry.User;
import com.xcc.common.domain.service.UserService;
/**
 *@description  
 * @date   2019-11-19 19:17:06
 * @author  frosty
 */ 
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{


    @Autowired
    public  UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ResultBody listByPage(Map<String,Object> map) {
        PageParam page=new PageParam(map);
        User query = page.mapToObj(User.class);
        page.setRecords(userMapper.listByPage(page,query));
        return  ResultBody.success(page);
    }

    @Override
    public ResultBody login(String username, String password) {
        if(StringUtils.isBlank(username)|| StringUtils.isBlank(password)){
            return  ResultBody.error("用户名或密码不能为空");
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_name",username);
        User user = userMapper.selectOne(queryWrapper);
        if(user!=null){
            if(password.equals(user.getPassword())){
                String token = IdWorker.getIdStr();
                redisUtil.lSet(user.getId(),token);
                List<Object> objects = redisUtil.lGet(user.getId(), 0, -1);
                if(objects!=null&&objects.size()> LoginConfig.MAX_LOGIN_TIME){
                    //保留的list
                    List list1=  objects.subList(objects.size()-LoginConfig.MAX_LOGIN_TIME,objects.size());
                 //需要删除的token
                    List list2=objects.subList(0,objects.size()-LoginConfig.MAX_LOGIN_TIME);
                    String [] delToken=new String[list2.size()];
                    for (int i=0;i<list2.size();i++) {
                        delToken[i]=(String)list2.get(i);
                    }
                    redisUtil.del(user.getId());
                    boolean b = redisUtil.lSet(user.getId(), list1);
                    redisUtil.del(delToken);
                }
                redisUtil.set(token,user,LoginConfig.TOKEN_TIME);
                Map<String,Object> t_m=new HashMap<>();
                t_m.put("token",token);
                t_m.put("user",user);
                return ResultBody.success(t_m);
            }
        }

        return ResultBody.error("用户名或密码错误!");
    }

}
